<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言简单的koa框架使用示例如下代码，我们写一个简单的中间件 12345678910111213141516171819202122232425262728293031const Koa &#x3D; require(&#39;koa&#39;);const app &#x3D; new Koa();&#x2F;&#x2F;日志中间件app.use(async (ctx, next) &#x3D;&gt; &amp;#123;    const start &#x3D; new">
<meta property="og:type" content="article">
<meta property="og:title" content="koa框架入门">
<meta property="og:url" content="http://example.com/2021/10/20/node/Koa%E6%A1%86%E6%9E%B6%E5%85%A5%E9%97%A8/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言简单的koa框架使用示例如下代码，我们写一个简单的中间件 12345678910111213141516171819202122232425262728293031const Koa &#x3D; require(&#39;koa&#39;);const app &#x3D; new Koa();&#x2F;&#x2F;日志中间件app.use(async (ctx, next) &#x3D;&gt; &amp;#123;    const start &#x3D; new">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-20T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-03T08:19:47.893Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="Koa框架">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/10/20/node/Koa%E6%A1%86%E6%9E%B6%E5%85%A5%E9%97%A8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>koa框架入门 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/20/node/Koa%E6%A1%86%E6%9E%B6%E5%85%A5%E9%97%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          koa框架入门
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-10-20 12:18:39" itemprop="dateCreated datePublished" datetime="2021-10-20T12:18:39+08:00">2021-10-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:19:47" itemprop="dateModified" datetime="2021-11-03T16:19:47+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>简单的koa框架使用示例如下代码，我们写一个简单的中间件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"></span><br><span class="line"><span class="comment">//日志中间件</span></span><br><span class="line">app.use(<span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> start = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'[logger middleware] before await...'</span>);</span><br><span class="line">    <span class="keyword">await</span> next();</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'[logger middleware] after await...'</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">const</span> ms = <span class="keyword">new</span> <span class="built_in">Date</span>() - start;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'$&#123;ctx.method&#125; $&#123;ctx.url&#125; - $&#123;ms&#125;ms'</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//响应</span></span><br><span class="line">app.use(<span class="keyword">async</span> ctx =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'[response middleware] response...'</span>);</span><br><span class="line">    ctx.body = <span class="string">'Hello Koa2'</span></span><br><span class="line">&#125;)</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出如下：</span></span><br><span class="line"><span class="comment">[logger middleware] before await...</span></span><br><span class="line"><span class="comment">[response middleware] response...</span></span><br><span class="line"><span class="comment">[logger middleware] after await...</span></span><br><span class="line"><span class="comment">GET / -7ms</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">这三处日志的输出很明显是在logger中间件的await next()代码前后进行处理的，通过await next()将执行权交给下一个中间件，即response中间件.</span></span><br><span class="line"><span class="comment">于是代码就截止async函数变成顺序执行了。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>要点：1、中间件支持async函数+箭头函数；2、参数除了next参数，还有上下文ctx参数，作为显式的上下文。</p>
<h2 id="框架演进"><a href="#框架演进" class="headerlink" title="框架演进"></a>框架演进</h2><p>Connect：是一个用Node.js编写的可扩展的HTTP服务器端框架，最早的Node服务端框架。</p>
<p>1、基于http.createServer；createServer的参数是独立的，而Connect里通过app.use()函数可以挂载多个插件式的中间件。</p>
<p>2、Connect提供了一个独立的app层，通过app.use函数来挂载中间件。提供了可变部分的插件化，而将不可变部分固定。</p>
<p>app.use的中间件是有顺序的；且中间件可分类，分为全局的和局部的（路由中生效的）；中间件的定义方法是function(req, res){}。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> connect = <span class="built_in">require</span>(<span class="string">'connect'</span>);</span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="keyword">var</span> app = connect();</span><br><span class="line"></span><br><span class="line"><span class="comment">//对响应进行gzip压缩</span></span><br><span class="line"><span class="keyword">var</span> compression = <span class="built_in">require</span>(<span class="string">'compression'</span>);</span><br><span class="line">app.use(compression());</span><br><span class="line"><span class="comment">//在浏览器缓存里存取会话状态</span></span><br><span class="line"><span class="keyword">var</span> cookieSession = <span class="built_in">require</span>(<span class="string">'cookie-session'</span>);</span><br><span class="line">app.use(cookieSession(&#123;</span><br><span class="line">    keys: [<span class="string">'secret1'</span>, <span class="string">'secret2'</span>]</span><br><span class="line">&#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">//解析urlencoded的请求体，并赋值给req.body</span></span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line">app.use(bodyParser.urlencoded(&#123;<span class="attr">extended</span>: <span class="literal">false</span>&#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">//响应所有请求</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    res.end(<span class="string">'Hello from Connect!\n'</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//启动服务器</span></span><br><span class="line">http.createServer(app).listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>

<p>Express的使用实例和Connect基本一样，只有模块引用不同。Express的启动方式有以下两种：1、通过内置的app.listen使用；2、使用http模块http.createServer(app)，可以完成更多定制功能。</p>
<p>和Express类似，KOA也对原始的http模块进行了抽象封装，只是中间件形式不一样。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"><span class="comment">//响应所有请求</span></span><br><span class="line">app.use(<span class="keyword">async</span> ctx =&gt; &#123;</span><br><span class="line">    ctx.body = <span class="string">'Hello Koa 2'</span>;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> server = http.createServer(app.callback());</span><br><span class="line">server.listen(<span class="number">3000</span>);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">很明显，Koa把http.createServer里的内容封装到了app.callback()里。</span></span><br><span class="line"><span class="comment">app是Koa对象；app.use里使用的是Koa中间件写法；</span></span><br><span class="line"><span class="comment">app.callback()把app.use里的内容转成了function(req, res)&#123;...&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h1 id="中间件"><a href="#中间件" class="headerlink" title="中间件"></a>中间件</h1><p>中间件是框架的扩展机制，主要用于抽象HTTP请求过程；在单一请求响应过程中加入中间件，可以更好地应付复杂的业务逻辑。</p>
<p>KoaV2最重要的特性是支持async函数，且同时支持如下3中不同类型函数的中间件。</p>
<p>1、通用函数中间件，是最常用的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"><span class="comment">//日志</span></span><br><span class="line">app.use(<span class="function">(<span class="params">ctx, next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> start = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line">    <span class="keyword">return</span> next().then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> ms = <span class="keyword">new</span> <span class="built_in">Date</span>() - start;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'$&#123;ctx.method&#125; $&#123;ctx.url&#125; - $&#123;ms&#125;ms'</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//响应</span></span><br><span class="line">app.use(<span class="function"><span class="params">ctx</span> =&gt;</span> &#123;</span><br><span class="line">    ctx.body = <span class="string">'Hello Koa'</span>;</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>

<p>(ctx, next) =&gt; {}，它有两个参数，ctx为上下文，包括所有的请求和响应；而next()是确定当前中间件是否将请求向下一个中间件放行的函数。</p>
<p>2、生成器函数</p>
<p>生成器函数中间件被co.wrap包裹并转换；其参数中多了ctx；从该中间件跳转下一中间件是通过：yield next()函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"><span class="comment">//日志</span></span><br><span class="line">app.use(co.wrap(<span class="function"><span class="keyword">function</span> *(<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> start = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line">    <span class="keyword">yield</span> next();</span><br><span class="line">    <span class="keyword">const</span> ms = <span class="keyword">new</span> <span class="built_in">Date</span>() - start;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'$&#123;ctx.method&#125; $&#123;ctx.url&#125; - $&#123;ms&#125;ms'</span>);</span><br><span class="line">&#125;));</span><br><span class="line"><span class="comment">//响应</span></span><br><span class="line">app.use(<span class="function"><span class="params">ctx</span> =&gt;</span> &#123;</span><br><span class="line">    ctx.body = <span class="string">'Hello Koa'</span>;</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>

<p>3、async函数中间件</p>
<p>await可以无缝调用异步Promise方法，更好地向后兼容。async函数跳转到下一个中间件时，需要使用await next()。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"><span class="comment">//日志</span></span><br><span class="line">app.use(<span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> start = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line">    <span class="keyword">await</span> next();</span><br><span class="line">    <span class="keyword">const</span> ms = <span class="keyword">new</span> <span class="built_in">Date</span>() - start;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'$&#123;ctx.method&#125; $&#123;ctx.url&#125; - $&#123;ms&#125;ms'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//响应</span></span><br><span class="line">app.use(<span class="function"><span class="params">ctx</span> =&gt;</span> &#123;</span><br><span class="line">    ctx.body = <span class="string">'Hello Koa'</span>;</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>

<h2 id="上下文对象"><a href="#上下文对象" class="headerlink" title="上下文对象"></a>上下文对象</h2><p>在web应用中，Koa的上下文对象ctx是一次完整的HTTP请求的上下文，贯穿这个请求的生命周期。请求会经过N层中间件的拦截，唯一共享的就是这个上下文对象。它主要封装了request对象和response对象，并提供了一些帮助开发者编写业务逻辑的方法，我们可以在ctx.request和ctx.response中很方便地访问这些方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这里统一把上下文定为ctx</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span> *(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> ctx = <span class="keyword">this</span>;<span class="comment">//上下文对象</span></span><br><span class="line">    <span class="keyword">this</span>.request;</span><br><span class="line">    <span class="keyword">this</span>.response;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//每个请求至少贯穿一个中间件</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span> *(<span class="params">next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> ctx = <span class="keyword">this</span>;</span><br><span class="line">    ctx.a = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">yield</span> next();</span><br><span class="line">    <span class="built_in">console</span>.log(ctx.a)<span class="comment">//此时打印2</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span> *(<span class="params">next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> ctx = <span class="keyword">this</span>;</span><br><span class="line">    ctx.a = <span class="number">2</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">由于第二个中间件中没有next命令，所以结束响应，返回第一个中间件next()后面。</span></span><br><span class="line"><span class="comment">ctx的生命周期是贯穿整个HTTP请求过程的，在ctx上绑定内容不是一个好的做法，但适当地在ctx上下文绑定某些内容是必要的，</span></span><br><span class="line"><span class="comment">例如：日志中间件，ctx.render()函数。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>ctx上常用的对象有request、response、req、res等，其中request和response是Koa内置的对象，是对HTTP的实用扩展；而req和res是在http.createServer回调函数里注入的，即未经加工的原生内置对象。</p>
<p>之前说过，Koa提供的中间件机制是对http.createServer回调进行抽象；也就是说，app里被注入了http.createServer的回调函数，核心是app.callback()实现。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用方法如下：</span></span><br><span class="line"><span class="keyword">const</span> server = http.createServer(app.callback());</span><br><span class="line"></span><br><span class="line"><span class="comment">//callback的实现代码如下：在Koa源码application.js中。</span></span><br><span class="line">callback() &#123;</span><br><span class="line">    <span class="keyword">const</span> fn = compose(<span class="keyword">this</span>.middleware);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.listeners(<span class="string">'error'</span>).length) <span class="keyword">this</span>.on(<span class="string">'error'</span>, <span class="keyword">this</span>.onerror);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">const</span> handleRequest = <span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">        res.statusCode = <span class="number">404</span>;</span><br><span class="line">        <span class="keyword">const</span> ctx = <span class="keyword">this</span>.createContext(req, res);</span><br><span class="line">        <span class="keyword">const</span> onerror = <span class="function"><span class="params">err</span> =&gt;</span> ctx.onerror(err);</span><br><span class="line">        <span class="keyword">const</span> handleResponse = <span class="function"><span class="params">()</span> =&gt;</span> respond(ctx);</span><br><span class="line">        onFinished(res, onerror);</span><br><span class="line">        <span class="keyword">return</span> fn(ctx).then(handleResponse).catch(onerror);</span><br><span class="line">    &#125;;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> handleRequest;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//其中的核心const ctx = this.createContext(req, res);表示进行了绑定，其源码如下：</span></span><br><span class="line">createContext(req, res) &#123;</span><br><span class="line">    <span class="keyword">const</span> context = <span class="built_in">Object</span>.create(<span class="keyword">this</span>.context);</span><br><span class="line">     <span class="comment">// 使用Object.create方法是为了继承this.context但在增加属性时不影响原对象;继承属性，且不影响原对象</span></span><br><span class="line">    <span class="keyword">const</span> request = context.request = <span class="built_in">Object</span>.create(<span class="keyword">this</span>.request);<span class="comment">//Koa内置的request对象</span></span><br><span class="line">    <span class="keyword">const</span> response = context.response = <span class="built_in">Object</span>.create(<span class="keyword">this</span>.response);<span class="comment">//Koa内置的response对象</span></span><br><span class="line">    </span><br><span class="line">     <span class="comment">// 下面的操作是为了把ctx中的属性与request、response中的属性联系起来，其实就是将后两者中定义的方法挂载到ctx上</span></span><br><span class="line">    <span class="comment">//这样，我们后续就可以在ctx中用简洁的写法来访问各种属性了</span></span><br><span class="line">    context.app = request.app = response.app = <span class="keyword">this</span>;<span class="comment">//app自身</span></span><br><span class="line">    context.req = request.req = response.req = req;<span class="comment">//赋值为原始HTTP回调函数里的req对象</span></span><br><span class="line">    context.res = request.res = response.res = res;<span class="comment">//赋值为原始HTTP回调函数里的res对象</span></span><br><span class="line">    request.ctx = response.ctx = context;</span><br><span class="line">    request.response = response;</span><br><span class="line">    response.request = request;</span><br><span class="line">    context.originalUrl = request.originalUrl = req.url;<span class="comment">//originalUrl是最初的URL地址</span></span><br><span class="line">    context.cookies = <span class="keyword">new</span> Cookies(req, res, &#123;</span><br><span class="line">        keys: <span class="keyword">this</span>.keys,</span><br><span class="line">        secure: request.secure</span><br><span class="line">    &#125;);<span class="comment">//context.cookies是浏览器cookie封装</span></span><br><span class="line">    request.ip = request.ips[<span class="number">0</span>] || req.socket.remoteAddress || <span class="string">""</span>;</span><br><span class="line">    context.accept = request.accept = accepts(req);</span><br><span class="line">    context.state = &#123;&#125;;</span><br><span class="line">    <span class="comment">//context.state = &#123;&#125;约定了一个中间件的公用存储空间，可以存储一些数据。</span></span><br><span class="line">    <span class="keyword">return</span> context;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="request和response"><a href="#request和response" class="headerlink" title="request和response"></a>request和response</h2><p>为了使用方便，许多上下文属性和方法都被委托代理到了Koa的ctx.request或ctx.response上。</p>
<p>基于以上关系，想要对Stream进行扩展就十分容易了，分别在request.js和response.js上对处理方式进行扩展。</p>
<p>而对于ctx.request和ctx.response没有实现的功能，可以通过扩展ctx.req和ctx.res来实现。这两者是更低级别的API，是http.createServer的回调函数传进来的参数，通过它们可以实现更多功能。</p>
<p>例如：koa-bigpipe中间件就是通过原始的res.write来实现BigPipe分块写入功能的。http模块的res.write()默认是支持分块传输的，所以遵循Koa中间件约定并提供ctx.write和ctx.end方法，能够更好地以Koa的方式编写BigPipe。</p>
<p>Bigpipe适用场景：</p>
<p>如果一个页面，在服务端渲染中，数据源比较多的情况下，我们需要等待所有的请求都返回数据才进行html拼接并返回，这样我们页面最终渲染的速度就限制在最迟返回数据的请求上了。</p>
<p>那针对上述数据源较多的情况，还有优化的方案吗？答案就是Bigpipe。</p>
<p>Bigpipe是一种采用流的方式对页面进行渲染的机制，在浏览器请求页面时，打开管道后持续对页面的块进行输出。块A、B、C拼装好块之后直接通过开始建立的管道输出到页面中，这样页面的最终输出就不需要依赖最后一个块的拼装时间了。</p>
<h3 id="浏览器交互"><a href="#浏览器交互" class="headerlink" title="浏览器交互"></a>浏览器交互</h3><p>Koa框架与浏览器交互的方式主要是让服务器对浏览器进行响应，有三种可用方法。</p>
<p>1、ctx.body(Koa内置)：</p>
<p>ctx.body能够以最精简的代码实现最多的功能，返回文本、HTML输出或者JSON。</p>
<p>工作原理：1、根据body的类型设置对应Content-Type；2、根据Content-Type调用res.write或res.end，将数据写入浏览器。</p>
<p>2、ctx.redirect</p>
<p>浏览器重定向只有两种情况，向前重定向和向后重定向，</p>
<p>3、ctx.render是渲染模板适用的方法，有两个参数：模板和数据。该方法主要用于将模板编译成HTML并写入浏览器。</p>
<p>Koa v1的中间件机制其实就是将compose([f1,f2,…,fn])转化成fn(…f2(f1(noop())))，最终的返回值是一个生成器函数。而Koa v2的中间件机制是将compose([f1,f2,…,fn])转化为f1(…f(n-1)(fn(noop())))，最终的返回值是一个function (context, next) {}。即使返回值是function *(next){}，也会被转换为function(context, next) {}，这是convert的向后兼容特性。</p>
<h2 id="常用中间件"><a href="#常用中间件" class="headerlink" title="常用中间件"></a>常用中间件</h2><p>分为三类：Pre-Request：通常用于改写请求的原始数据；Request/Response：大部分中间件，功能各异；Post-Response：进行全局异常处理，改写响应数据之类的。</p>
<p>koa-compress：实现gzip压缩的中间件；koa-conditional-get和koa-etag：提供ETag使用的中间件；koa-favicon：是简单的Favicon中间件；koa-static：提供静态HTTP资源托管的中间件。</p>
<h1 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h1><p>koa框架是小而美的设计，本身没有内置路由，但是允许开发者使用各类插件实现功能。Koa中最常使用的是koa-router插件。</p>
<p>路由的本质是对ctx.path进行抽象，其实现原理：1、定义路由；2、路由的路径会被转译成正则表达式；3、匹配请求，使用中间件进行处理。</p>
<p>koa-router模块的核心是路由解析，使用的是path-to-regexp模块，与Express所使用的模块一致。</p>
<p>路由的四种形式：1、普通路由，如：’/users’；2、具名路由，如：’/user/:id’；具名路由由参数通过ctx.params来获取；</p>
<p>3、正则路由，如：’/^/commits/(\w+)(?:..(\w+))?$/‘</p>
<p>4、嵌套路由：即不同实体之间是一对多的关系，是上面多种路由形式的组合。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//路由也是中间件，其定义方法如下：</span></span><br><span class="line">router.use([path], middleware, [...]) =&gt; Router;</span><br><span class="line"><span class="comment">//简单的路由实例如下：</span></span><br><span class="line">router.get(<span class="string">'/users/:id'</span>,</span><br><span class="line">           <span class="function"><span class="keyword">function</span> (<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> User.findOne(ctx.params.id).then(<span class="function"><span class="keyword">function</span>(<span class="params">user</span>) </span>&#123;</span><br><span class="line">        ctx.user = user;</span><br><span class="line">        <span class="keyword">return</span> next();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;,<span class="function"><span class="keyword">function</span> (<span class="params">ctx</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(ctx.user);</span><br><span class="line">    <span class="comment">// =&gt; &#123;id:17, name:"Alex"&#125;</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">在该例子中，第一个中间件根据ID查询到的用户，先被绑定到了ctx对象上；然后交给了下一个中间件进行处理。</span></span><br><span class="line"><span class="comment">接着，第二个中间件根据第一个中间件产生的ctx.user完成某些内容，最终决定返回何值。</span></span><br><span class="line"><span class="comment">由多种中间件组成的路由可以完成以下事情：</span></span><br><span class="line"><span class="comment">1、解耦代码，将代码拆分得更细致；</span></span><br><span class="line"><span class="comment">2、实现模块化，通过组装中间件来完成逻辑；</span></span><br><span class="line"><span class="comment">3、实现权限类、日志类得AOP（面向切面编程）</span></span><br><span class="line"><span class="comment">4、实现与Hook类似的抽象</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h2 id="视图"><a href="#视图" class="headerlink" title="视图"></a>视图</h2><p>按照koa-generator里的选型，Koa默认使用的视图模板引擎仍然是Pug，koa-views是最好用的一个视图模块。</p>
<h2 id="静态服务模块"><a href="#静态服务模块" class="headerlink" title="静态服务模块"></a>静态服务模块</h2><p>一般我们使用koa-static模块来托管静态资源。使用该模块，我们可以将前端常用的JS、CSS、JSON均通过本地静态服务器来提供。而静态资源托管的具体是如何实现的呢：koa-static依赖两个模块，分别为debug和koa-send。</p>
<p>koa-static源码的index.js代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> send = <span class="built_in">require</span>(<span class="string">'koa-send'</span>);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">serve</span> (<span class="params">root, opts</span>) </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">serve</span> (<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">await</span> next();</span><br><span class="line">        <span class="keyword">if</span> (ctx.method !== <span class="string">'HEAD'</span> &amp;&amp; ctx.method !== <span class="string">'GET'</span>) <span class="keyword">return</span> </span><br><span class="line">        <span class="keyword">if</span> (ctx.body !== <span class="literal">null</span> || ctx.status !== <span class="number">404</span>) <span class="keyword">return</span> <span class="comment">//eslint-disable-line</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">await</span> send(ctx, ctx.path, opts)</span><br><span class="line">        &#125; <span class="keyword">catch</span>(err) &#123;</span><br><span class="line">            <span class="keyword">if</span> (err.status !== <span class="number">404</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> err;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由上面的示例可以看出，其中的核心是send代码，即koa-send提供的。其实为文件提供HTTP服务是非常简答的，而koa-send就是做的这件事情：提供一个相对完善且小而美的处理静态文件的Koa中间件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//其源码示例如下：</span></span><br><span class="line"><span class="keyword">if</span> (!ctx.type) ctx.type = type(path, encodingExt);</span><br><span class="line">ctx.body = fs.createReadStream(path);</span><br><span class="line"></span><br><span class="line"><span class="comment">//其中的ctx.type是根据文件后缀来设置Content-Type的便捷方法</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">type</span>(<span class="params">file, ext</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> ext !== <span class="string">''</span> ? extname(basename(file, ext)) : extname(file);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">基本原理总结如下：</span></span><br><span class="line"><span class="comment">1、设置Content-Type，可通过文件后缀机型设置；</span></span><br><span class="line"><span class="comment">2、以Stream的形式为ctx.body赋值，这种方式比fs.readFileSync更高效。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>koa-mount：将中间件挂载到指定路径的Koa中间件，它可以挂载任意Koa中间件；而koa-static是Koa中间件，所以koa-static与koa-mount结合就可以实现和express一样的静态服务器带有请求前缀的功能。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/10/20/node/Koa%E6%A1%86%E6%9E%B6%E5%85%A5%E9%97%A8/" title="koa框架入门">http://example.com/2021/10/20/node/Koa框架入门/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Koa%E6%A1%86%E6%9E%B6/" rel="tag"># Koa框架</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/19/node/%E5%BC%82%E6%AD%A5%E4%B8%8Easync/" rel="prev" title="异步与async">
      <i class="fa fa-chevron-left"></i> 异步与async
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/10/21/node/node%E4%B8%AD%E7%9A%84HTTP/" rel="next" title="node中的HTTP">
      node中的HTTP <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#框架演进"><span class="nav-number">1.1.</span> <span class="nav-text">框架演进</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#中间件"><span class="nav-number">2.</span> <span class="nav-text">中间件</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#上下文对象"><span class="nav-number">2.1.</span> <span class="nav-text">上下文对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#request和response"><span class="nav-number">2.2.</span> <span class="nav-text">request和response</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#浏览器交互"><span class="nav-number">2.2.1.</span> <span class="nav-text">浏览器交互</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常用中间件"><span class="nav-number">2.3.</span> <span class="nav-text">常用中间件</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路由"><span class="nav-number">3.</span> <span class="nav-text">路由</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#视图"><span class="nav-number">3.1.</span> <span class="nav-text">视图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#静态服务模块"><span class="nav-number">3.2.</span> <span class="nav-text">静态服务模块</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

